
import axios, { type AxiosInstance } from "axios";
import { ElMessage, ElLoading } from "element-plus";
import { wmsStore } from "@/store/pinia";

let loading: any
class http {


    instance: AxiosInstance;
    constructor() {
        this.instance = axios.create({
            baseURL: '',
            timeout: 5000,
            //headers: {'X-Custom-Header': 'foobar'}
        });
        // 1.添加请求拦截器， 再请求后端接口之前触发
        this.instance.interceptors.request.use(function (config) {
            let store = wmsStore()
            // 在发送请求之前做些什么
            loading = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)',
            })

            if (store.token != "") {
                config.headers.token = store.token
            }

            return config;
        }, function (error) {
            // 对请求错误做些什么
            return Promise.reject(error);
        });
        // 2.添加响应拦截器 获取到后端接口数据之后触发
        this.instance.interceptors.response.use(function (response) {
            // 对响应数据做点什么
            loading.close()
            const { code, message, data } = response.data
            if (code === undefined) {
                return response.data
            } else if (code === 0) {
                return data
            } else if (code === 403) {
                ElMessage.error(message)
                return data
                // window.location.href = '/user/login'
            } else {
                ElMessage.error(message)
                return Promise.reject(message)
            }
            return response;
        }, function (error) {
            // 对响应错误做点什么
            loading.close()
            return Promise.reject(error);
        });

    }

    get(url: string, params = {}) {

        return this.instance.get(url, { params: params })
    }
    post(url: string, body = {}) {
        return this.instance.post(url, body)
    }
    put(url: string, body = {}) {
        return this.instance.put(url, body)
    }
    delete(url: string, params = {}) {

        return this.instance.delete(url, { params: params })
    }
}

export default new http();